"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Download, Lock, FileText, Eye } from "lucide-react"
import { FilePreviewDialog } from "@/components/file-preview-dialog"
import { apiCall, mockGenerators } from "@/lib/mock-api"

interface SharedFileViewProps {
  shareId: string
}

export function SharedFileView({ shareId }: SharedFileViewProps) {
  const [password, setPassword] = useState("")
  const [file, setFile] = useState<any>(null)
  const [needPassword, setNeedPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState("")
  const [showPreview, setShowPreview] = useState(false)

  useEffect(() => {
    loadShareInfo()
  }, [shareId])

  const loadShareInfo = async () => {
    setIsLoading(true)
    setError("")

    try {
      const data = await apiCall(
        `/api/shares/${shareId}${password ? `?password=${password}` : ""}`,
        {},
        undefined,
        mockGenerators.sharedFile,
      )

      // code === 1，成功获取分享信息
      setFile(data.file)
      setNeedPassword(false)
    } catch (error: any) {
      // code === 2，需要密码或密码错误或分享失效
      const errorCode = error?.cause
      
      if (errorCode === 2) {
        // 如果是第一次请求（没有输入密码），显示密码输入框
        if (!password) {
          setNeedPassword(true)
          setError("")
        } else {
          // 如果已经输入了密码，说明密码错误
          setError("密码错误，请重新输入")
          setNeedPassword(true)
        }
      } else {
        // 其他错误情况
        setError("分享链接无效或已过期")
        setNeedPassword(false)
      }
    } finally {
      setIsLoading(false)
    }
  }

  const handleDownload = async () => {
    try {
      // 构建下载 URL，如果有密码则添加密码参数
      const downloadUrl = password 
        ? `/api/shares/${shareId}/download?password=${password}`
        : `/api/shares/${shareId}/download`
      
      const response = await fetch(downloadUrl)
      
      if (!response.ok) {
        throw new Error("下载失败")
      }
      
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement("a")
      a.href = url
      a.download = file.fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error("Download failed:", error)
      setError("下载失败，请重试")
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <p className="text-muted-foreground">加载中...</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-6">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-xl bg-primary">
            <FileText className="h-6 w-6 text-primary-foreground" />
          </div>
          <CardTitle>文件分享</CardTitle>
          <CardDescription>{file ? "有人向您分享了一个文件" : error || "验证访问权限"}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {needPassword && !file && (
            <>
              <div className="space-y-2">
                <Label htmlFor="password">访问密码</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    id="password"
                    type="text"
                    placeholder="请输入密码"
                    className="pl-10"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    maxLength={4}
                  />
                </div>
                {error && <p className="text-sm text-destructive">{error}</p>}
              </div>
              <Button className="w-full" onClick={loadShareInfo} disabled={password.length !== 4}>
                访问文件
              </Button>
            </>
          )}

          {file && (
            <>
              <div className="p-4 rounded-lg bg-muted">
                <p className="text-sm text-muted-foreground mb-1">文件名</p>
                <p className="font-medium">{file.fileName}</p>
              </div>
              <div className="p-4 rounded-lg bg-muted">
                <p className="text-sm text-muted-foreground mb-1">文件大小</p>
                <p className="font-medium">{(file.fileSize / (1024 * 1024)).toFixed(2)} MB</p>
              </div>
              <div className="flex gap-2">
                <Button className="flex-1 gap-2 bg-transparent" variant="outline" onClick={() => setShowPreview(true)}>
                  <Eye className="h-4 w-4" />
                  预览
                </Button>
                <Button className="flex-1 gap-2" onClick={handleDownload}>
                  <Download className="h-4 w-4" />
                  下载
                </Button>
              </div>
            </>
          )}

          {!needPassword && !file && error && <p className="text-sm text-destructive text-center">{error}</p>}
        </CardContent>
      </Card>

      {file && (
        <FilePreviewDialog 
          file={file} 
          open={showPreview} 
          onOpenChange={setShowPreview} 
          onDownload={() => handleDownload()} 
          shareId={shareId}
          sharePassword={password}
        />
      )}
    </div>
  )
}
